<template>
  <div class="book-management">
    <div class="header-with-back">
      <button class="back-btn" @click="$emit('back')">
        <el-icon><ArrowLeft /></el-icon> 返回
      </button>
      <h1 class="page-title">书籍管理</h1>
    </div>
    
    <LoadingSpinner v-if="isLoading" message="加载书籍数据..." />
    
    <div v-else class="book-management-content">
      <div class="filters-row">
        <div class="filter-group">
          <label>价格区间:</label>
          <select v-model="priceFilter">
            <option value="all">全部价格</option>
            <option value="0-20">20元以下</option>
            <option value="20-50">20-50元</option>
            <option value="50-100">50-100元</option>
            <option value="100+">100元以上</option>
          </select>
        </div>
        
        <div class="filter-group">
          <label>品相:</label>
          <select v-model="conditionFilter">
            <option value="all">全部品相</option>
            <option value="new">几乎全新</option>
            <option value="good">品相良好</option>
            <option value="used">有使用痕迹</option>
          </select>
        </div>
        
        <div class="filter-group">
          <label>排序方式:</label>
          <select v-model="sortBy">
            <option value="default">默认排序</option>
            <option value="price-asc">价格从低到高</option>
            <option value="price-desc">价格从高到低</option>
            <option value="condition">品相优先</option>
          </select>
        </div>
        
        <div class="search-box">
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索书名/作者..." 
            @input="handleSearch"
          >
        </div>
      </div>
      
      <div v-if="filteredBooks.length === 0" class="no-books">
        暂无书籍数据
      </div>
      
      <div v-else class="books-table-container">
        <table class="books-table">
          <thead>
            <tr>
              <th>封面</th>
              <th>书名</th>
              <th>作者</th>
              <th>价格</th>
              <th>品相</th>
              <th>卖家</th>
              <th>上架时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="book in filteredBooks" :key="book.id">
              <td>
                <img :src="getCoverUrl(book)" :alt="book.title" class="book-cover-thumbnail">
              </td>
              <td class="book-title">{{ book.title }}</td>
              <td>{{ book.author }}</td>
              <td class="book-price">¥{{ book.price }}</td>
              <td>
                <span v-if="book.book_condition === 'new'" class="tag tag-new">几乎全新</span>
                <span v-else-if="book.book_condition === 'good'" class="tag tag-good">品相良好</span>
                <span v-else-if="book.book_condition === 'used'" class="tag tag-used">有使用痕迹</span>
              </td>
              <td>{{ book.seller_name }}</td>
              <td>{{ formatDate(book.created_at) }}</td>
              <td>
                <button class="btn btn-danger" @click="confirmDeleteBook(book)">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    
    <!-- 确认删除对话框 -->
    <div class="modal" v-if="showDeleteModal">
      <div class="modal-content">
        <h3>确认删除</h3>
        <p>确定要删除书籍 "{{ selectedBook?.title }}" 吗？此操作不可恢复。</p>
        <div class="modal-actions">
          <button class="btn btn-secondary" @click="showDeleteModal = false">取消</button>
          <button class="btn btn-danger" @click="deleteBook">确认删除</button>
        </div>
      </div>
    </div>
    
    <!-- Toast通知组件 -->
    <Toast 
      :message="toastMessage" 
      :type="toastType" 
      :visible="showToast" 
      @close="showToast = false" 
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import api from '@/api/apiClient'
import Toast from '@/components/Toast.vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import defaultCover from '@/assets/OIP.jpg'
import { ArrowLeft } from '@element-plus/icons-vue'

// 定义事件
defineEmits(['back'])

// 状态变量
const books = ref([])
const isLoading = ref(true)
const showToast = ref(false)
const toastMessage = ref('')
const toastType = ref('info')
const priceFilter = ref('all')
const conditionFilter = ref('all')
const sortBy = ref('default')
const searchQuery = ref('')
const showDeleteModal = ref(false)
const selectedBook = ref(null)

// 显示通知
const showNotification = (message, type = 'info') => {
  toastMessage.value = message
  toastType.value = type
  showToast.value = true
}

// 获取书籍数据
const fetchBooks = async () => {
  isLoading.value = true
  try {
    // 获取所有书籍，只调用一次API
    const response = await api.book.getList({})
    
    // 输出响应进行调试
    console.log('原始响应:', response)
    
    // 检查响应格式并提取数据
    if (Array.isArray(response)) {
      // 如果是数组，直接使用
      books.value = response
      console.log('获取书籍数据成功 (数组格式):', books.value)
    } else if (response && response.code == 200 && response.data) {
      // 如果是包含code和data的对象，则使用response.data
      books.value = response.data
      console.log('获取书籍数据成功 (对象格式):', books.value)
    } else {
      console.error('获取书籍数据失败: 返回格式不正确', response)
      books.value = [] // 失败时设置为空数组
    }
  } catch (error) {
    console.error('获取书籍数据失败:', error)
    books.value = []
    showNotification('获取书籍数据失败', 'error')
  } finally {
    isLoading.value = false
  }
}

// 价格区间筛选
const getPriceRange = (book, range) => {
  const price = parseFloat(book.price);
  switch(range) {
    case '0-20': return price <= 20;
    case '20-50': return price > 20 && price <= 50;
    case '50-100': return price > 50 && price <= 100;
    case '100+': return price > 100;
    default: return true;
  }
}

// 品相筛选
const getCondition = (book, condition) => {
  switch(condition) {
    case 'new': return book.book_condition === 'new';
    case 'good': return book.book_condition === 'good';
    case 'used': return book.book_condition === 'used';
    default: return true;
  }
}

// 搜索函数
const handleSearch = () => {
  console.log('搜索内容:', searchQuery.value)
}

// 筛选和排序后的书籍列表
const filteredBooks = computed(() => {
  if (books.value.length === 0) return [];
  
  // 先筛选
  let result = books.value.filter(book => {
    const priceMatches = getPriceRange(book, priceFilter.value);
    const conditionMatches = getCondition(book, conditionFilter.value);
    const searchMatches = searchQuery.value === '' || 
      book.title?.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      book.author?.toLowerCase().includes(searchQuery.value.toLowerCase());
    
    return priceMatches && conditionMatches && searchMatches;
  });
  
  // 再排序
  if (sortBy.value === 'price-asc') {
    result.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
  } else if (sortBy.value === 'price-desc') {
    result.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
  } else if (sortBy.value === 'condition') {
    const conditionValue = (condition) => {
      switch(condition) {
        case 'new': return 3;
        case 'good': return 2;
        case 'used': return 1;
        default: return 0;
      }
    };
    
    result.sort((a, b) => conditionValue(b.book_condition) - conditionValue(a.book_condition));
  }
  
  return result;
})

// 获取封面URL
const getCoverUrl = (book) => {
  if (!book || !book.cover) {
    console.log('无封面数据，使用默认封面');
    return defaultCover;
  }
  
  try {
    // 尝试使用API helper函数
    if (typeof api.getCoverUrl === 'function') {
      const url = api.getCoverUrl(book);
      if (url) return url;
    }

    // 检查是否为相对路径，添加基础URL
    if (typeof book.cover === 'string') {
      if (!book.cover.startsWith('http')) {
        const encodedPath = book.cover.split('/').map(segment => encodeURIComponent(segment)).join('/');
        return `http://localhost:8080/${encodedPath}`;
      }
      return book.cover;
    }
    
    // 如果book.cover不是字符串，使用默认封面
    return defaultCover;
  } catch (error) {
    console.error('获取封面URL时出错:', error);
    return defaultCover;
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

// 确认删除书籍
const confirmDeleteBook = (book) => {
  selectedBook.value = book;
  showDeleteModal.value = true;
}

// 删除书籍
const deleteBook = async () => {
  if (!selectedBook.value) return;
  
  try {
    await api.admin.deleteBook(selectedBook.value.id);
    showNotification(`书籍 "${selectedBook.value.title}" 已成功删除`, 'success');
    
    // 从列表中移除已删除的书籍
    books.value = books.value.filter(book => book.id !== selectedBook.value.id);
    
    // 关闭对话框
    showDeleteModal.value = false;
    selectedBook.value = null;
  } catch (error) {
    console.error('删除书籍失败:', error);
    showNotification('删除书籍失败: ' + (error.message || '未知错误'), 'error');
  }
}

// 预加载所有封面
const preloadAllCovers = async () => {
  if (books.value.length === 0) return;
  console.log('开始预加载封面图片...');
  
  const preloadPromises = books.value.map(book => {
    return new Promise((resolve) => {
      const img = new Image();
      img.onload = () => resolve();
      img.onerror = () => resolve(); // 即使加载失败也继续
      img.src = getCoverUrl(book);
    });
  });
  
  try {
    await Promise.all(preloadPromises);
    console.log('封面图片预加载完成');
  } catch (error) {
    console.error('封面预加载出错:', error);
  }
}

// 组件加载时获取数据
onMounted(async () => {
  await fetchBooks()
  if (books.value.length > 0) {
    await preloadAllCovers()
  }
})
</script>

<style scoped>
.book-management {
  width: 100%;
  position: relative;
}

.header-with-back {
  display: flex;
  align-items: center;
  margin-bottom: 2rem;
}

.back-btn {
  display: flex;
  align-items: center;
  background: none;
  border: none;
  color: #3b82f6;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  padding: 0.5rem 0.75rem;
  margin-right: 1rem;
  border-radius: 4px;
}

.back-btn:hover {
  background-color: #eff6ff;
}

.back-btn i {
  margin-right: 0.25rem;
}

.page-title {
  margin-bottom: 0;
  font-size: 1.8rem;
  color: #374151;
}

.book-management-content {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 1.5rem;
}

.filters-row {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #e5e7eb;
}

.filter-group {
  display: flex;
  flex-direction: column;
  min-width: 160px;
}

.filter-group label {
  font-size: 0.875rem;
  color: #4b5563;
  margin-bottom: 0.25rem;
}

.filter-group select {
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.875rem;
}

.search-box {
  flex-grow: 1;
  display: flex;
  align-items: flex-end;
}

.search-box input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.875rem;
}

.no-books {
  text-align: center;
  padding: 3rem 0;
  color: #6b7280;
  font-size: 1.1rem;
}

.books-table-container {
  overflow-x: auto;
}

.books-table {
  width: 100%;
  border-collapse: collapse;
}

.books-table th,
.books-table td {
  padding: 0.75rem 1rem;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.books-table th {
  background-color: #f9fafb;
  font-weight: 500;
  color: #374151;
}

.book-cover-thumbnail {
  width: 50px;
  height: 70px;
  object-fit: cover;
  border-radius: 4px;
}

.book-title {
  font-weight: 500;
  color: #1f2937;
}

.book-price {
  font-weight: 600;
  color: #ef4444;
}

.tag {
  display: inline-block;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
}

.tag-new {
  background-color: #dcfce7;
  color: #166534;
}

.tag-good {
  background-color: #fef3c7;
  color: #92400e;
}

.tag-used {
  background-color: #fee2e2;
  color: #991b1b;
}

.btn {
  padding: 0.375rem 0.75rem;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  border: none;
}

.btn-danger {
  background-color: #ef4444;
  color: white;
}

.btn-danger:hover {
  background-color: #dc2626;
}

.btn-secondary {
  background-color: #9ca3af;
  color: white;
}

.btn-secondary:hover {
  background-color: #6b7280;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  padding: 1.5rem;
  width: 100%;
  max-width: 400px;
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.modal-content h3 {
  margin-top: 0;
  color: #1f2937;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.75rem;
  margin-top: 1.5rem;
}

@media (max-width: 768px) {
  .filters-row {
    flex-direction: column;
    gap: 0.75rem;
  }
  
  .filter-group,
  .search-box {
    width: 100%;
  }
}
</style> 